const VALIDATE_NO_PASSED = Symbol()
export {VALIDATE_NO_PASSED}

export function getRefPromise(vm, name) {
  return new Promise((resolve) => {
    (function next() {
      let ref = vm.$refs[name]
      if (ref) {
        resolve(ref)
      } else {
        setTimeout(() => {
          next()
        }, 10)
      }
    })()
  })
}

export function validateFormAndTables(form, cases) {

  if (!(form && typeof form.validateFields === 'function')) {
    throw `form 参数需要的是一个form对象，而传入的却是${typeof form}`
  }

  let options = {}
  return new Promise((resolve, reject) => {
    // 验证主表表单
    form.validateFields((err, values) => {
      err ? reject({error: VALIDATE_NO_PASSED}) : resolve(values)
    })
  }).then(values => {
    Object.assign(options, {formValue: values})
    // 验证所有子表的表单
    return validateTables(cases)
  }).then(all => {
    Object.assign(options, {tablesValue: all})
    return Promise.resolve(options)
  }).catch(error => {
    return Promise.reject(error)
  })

}

export function validateTables(cases) {
  if (!(cases instanceof Array)) {
    throw `'validateTables'函数的'cases'参数需要的是一个数组，而传入的却是${typeof cases}`
  }
  return new Promise((resolve, reject) => {
    let tables = []
    let index = 0;
    if (!cases || cases.length === 0) {
      resolve()
    }
    (function next() {
      let vm = cases[index]
      vm.getAll().then(all => {
        tables[index] = all
        // 判断校验是否全部完成，完成返回成功，否则继续进行下一步校验
        if (++index === cases.length) {
          resolve(tables)
        } else (
          next()
        )
      }, error => {
        // 出现未验证通过的表单，不再进行下一步校验，直接返回失败并跳转到该表格
        if (error === VALIDATE_NO_PASSED) {
          reject({error: VALIDATE_NO_PASSED, index})
        }
        reject(error)
      })
    })()
  })
}
//不校验必填获取表单数据方法
export function getFormAndTableValues(form, cases) {
  if (!(form && typeof form.validateFields === 'function')) {
    throw `form 参数需要的是一个form对象，而传入的却是${typeof form}`
  }
  return new Promise((resolve, reject) => {
    let options = {}
    Object.assign(options, {formValue: form.fieldsStore.getAllValues()})
    if (cases && cases.length > 0) {
      let tables = []
      for (let i = 0; i < cases.length; i++) {
        const {visibleData} = cases[i].$refs.xTable.getTableData()
        tables.push({
          values:visibleData
        })
      }
      Object.assign(options, {tablesValue: tables})
    }
    return resolve(options)
  }).catch(error => {
    return Promise.reject(error)
  })
}
